package queue;

import java.util.Iterator;

public class Queue<T> implements Iterable<T> {
    private Node head;
    private Node last;
    private int N;

    public Boolean isEmpty() {
        return N == 0;
    }

    public int size() {
        return N;
    }
    public Queue(){
        this.head = new Node(null,null);
        this.N = 0;
    }
    //向栈中增加元素
    public void enqueue(T t) {
        if (last == null) {
            last = new Node(t, null);
            head.next = last;
        } else {
            Node oldLast = last;
            last = new Node(t, null);
            oldLast.next = last;
        }
        N++;
    }

    public T dequeue() {
        if (isEmpty()) {
            return null;
        }
        Node first = head.next;
        Node two = first.next;
        head.next = two;
        N--;
        if (isEmpty()) {
            last = null;
        }
        return first.item;
    }

    @Override
    public Iterator<T> iterator() {
        return new ImIterator();
    }

    public class ImIterator implements Iterator {
        private Node n;

        public ImIterator() {
            this.n = head;
        }

        @Override
        public boolean hasNext() {

            return n.next != null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }
    }

    private class Node {
        T item;
        Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
}
